package com.spring.appservice.web.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.spera.genutil.TokenUtil;
import com.spring.appservice.web.dao.MessageBoardMapper;
import com.spring.appservice.web.service.MessageBoardService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.tools.MyTools;

@Service
public class MessageBoardServiceImpl implements MessageBoardService{
	
	@Resource
	private MongoTemplate mongoService;
	
	@Resource
	private JedisCache jedisCache;
	
	@Resource
	private MessageBoardMapper messageBoardMapper;
	/*
	@Override
	public Map<String, Object> queryMsgList(String token, String c_family_id,
			Integer pageNo, Integer pageSize, Integer skip, Integer row) {
		Map<String, Object> s = SpUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
		String user_id = jedisCache.lindex(token, 0);
		HashMap<String,Object> m=new HashMap<String,Object>();
		if(ApplicationUtils.isNotNull(c_family_id)){
			m.put("c_family_id", c_family_id);
		}else{
			m.put("c_user_id", user_id);
		}
		m.put("pid", 0);//查询的是父节点留言
		
		if(pageNo!=null&&pageSize!=null){//分页
			m.put("pageNo", (pageNo-1)*pageSize);
			m.put("pageSize", pageSize);
		}else if(skip!=null&&row!=null){//瀑布流
			m.put("skip", skip);
			m.put("row", row);
		}else{
			pageNo = 1;
			pageSize = 20;
			m.put("pageNo", (pageNo-1)*pageSize);
			m.put("pageSize", pageSize);
		}
		
		List<Map<String,Object>> dataSet = messageBoardMapper.queryMsgList(m);
		if(dataSet!=null&&dataSet.size()>0){
			List<Map<String,Object>> dataSet1 = new ArrayList<Map<String,Object>>();
			for(Map<String,Object> d:dataSet){
				dataSet1.add(d);
			}
			getMsgDetailById(dataSet,dataSet1,0,5);
		}
		s.put(ApplicationUtils.DATASET, dataSet);
		s.put(ApplicationUtils.STATUS, "1");
		s.put(ApplicationUtils.MSG, "查询成功");
		return s;
	}
	
	@Override
	public Map<String, Object> queryMsgDetailList(String token, String msg_id) {
		Map<String, Object> s = SpUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
//		jedisCache.lindex(token, 0);
		HashMap<String,Object> m=new HashMap<String,Object>();
		m.put("msg_id", msg_id);
		
		List<Map<String,Object>> dataSet = messageBoardMapper.queryMsgDetailList(m);
		if(dataSet!=null&&dataSet.size()>0){
			List<Map<String,Object>> dataSet1 = new ArrayList<Map<String,Object>>();
			for(Map<String,Object> d:dataSet){
				dataSet1.add(d);
			}
			getMsgDetailById(dataSet,dataSet1);
		}
		s.put(ApplicationUtils.DATASET, dataSet);
		s.put(ApplicationUtils.STATUS, "1");
		s.put(ApplicationUtils.MSG, "操作成功");
		return s;
	}

	@Override
	public Map<String, Object> addMessageBoard(String token,MessageBoard msgBoard) {
		Map<String, Object> s = SpUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
		String user_id = jedisCache.lindex(token, 0);
		msgBoard.setC_user_id(user_id);
		if(!ApplicationUtils.isNotNull(msgBoard.getC_family_id())){
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "家庭编号不可为空");
			return s;
		}
		if(!ApplicationUtils.isNotNull(msgBoard.getContent())){
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "内容不可为空");
			return s;
		}
		if(!ApplicationUtils.isNotNull(msgBoard.getMember_name())){
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "称谓不可为空");
			return s;
		}
		if(!ApplicationUtils.isNotNull(msgBoard.getMsg_pid())){
			msgBoard.setMsg_pid("0");
		}
		msgBoard.setMsg_id(ApplicationUtils.randomUUID());
		
		int i = messageBoardMapper.addMessageBoard(msgBoard);
		if(i==0){
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "保存失败");
		}else if(i==1){
			s.put(ApplicationUtils.STATUS, "1");
			s.put(ApplicationUtils.MSG, "保存成功");
		}else{
			s.put(ApplicationUtils.STATUS, "0");
			s.put(ApplicationUtils.MSG, "保存有误");
		}
		return s;
	}
	
	private void getMsgDetailById(List<Map<String,Object>> m,List<Map<String,Object>> pl){
		HashMap<String,Object> p=new HashMap<String,Object>();
		List<Map<String,Object>> npl = new ArrayList<Map<String,Object>>(); 
//		List<Map<String,Object>> nd = null;
		if(pl!=null&&pl.size()>0){
			for(Map<String,Object> d:pl){
				if(ApplicationUtils.isNotNull(d.get("msg_id"))){
					p.put("msg_pid", d.get("msg_id"));
					List<Map<String,Object>> dataSet = messageBoardMapper.queryMsgDetailList(p);
					//将数据插入结果集
					for(Map<String,Object> data:dataSet){
						m.add(data);
						npl.add(data);
					}
				}
			}
			if(npl!=null&&npl.size()>0){
				getMsgDetailById(m,npl);
			}
		}
	}
	*/
	/**
	 * 
	 * @param m  总记录
	 * @param pl 需要查询的子集
	 * @param nsize 当前递归次数
	 * @param tsize 限制递归次数
	
	private void getMsgDetailById(List<Map<String,Object>> m,List<Map<String,Object>> pl,int nsize,int tsize){
		HashMap<String,Object> p=new HashMap<String,Object>();
		List<Map<String,Object>> npl = new ArrayList<Map<String,Object>>(); 
//		List<Map<String,Object>> nd = null;
		if(pl!=null&&pl.size()>0){
			for(Map<String,Object> d:pl){
				if(ApplicationUtils.isNotNull(d.get("msg_id"))){
					p.put("msg_pid", d.get("msg_id"));
					List<Map<String,Object>> dataSet = messageBoardMapper.queryMsgDetailList(p);
					//将数据插入结果集
					for(Map<String,Object> data:dataSet){
						m.add(data);
						npl.add(data);
						if(nsize<=tsize){
							nsize++;
						}else{
							break;
						}
					}
				}
			}
			if(nsize<=tsize){
				if(npl!=null&&npl.size()>0){
					getMsgDetailById(m,npl,nsize,tsize);
				}
			}
		}
	} */

	/*@Override
	public Map<String, Object> removeMessageBoard(String token, String msg_id) {
		Map<String, Object> s = SpUtil.checkToken(token,jedisCache);
		if(ApplicationUtils.isNotNull(s))
			return s;
		s = new HashMap<String, Object>();
		List<String> l = new ArrayList<String>();
		l.add(msg_id);
		removeMsgById(l);
//		String user_id = jedisCache.lindex(token, 0);
		s.put(ApplicationUtils.STATUS, "1");
		s.put(ApplicationUtils.MSG, "删除成功");
		return s;
	}*/
	
	/**
	 * 递归删除
	 * @param msg_ids
	 
	private void removeMsgById(List<String> msg_ids){
		HashMap<String,Object> p=new HashMap<String,Object>();
		List<String> nid = new ArrayList<String>();
		if(msg_ids!=null&&msg_ids.size()>0){
			for(String id:msg_ids){
				if(ApplicationUtils.isNotNull(id)){
					p.put("msg_pid", id);
					//找出pid为id的记录
					List<Map<String,Object>> dataSet = messageBoardMapper.queryMsgDetailList(p);
					//将数据插入结果集
					for(Map<String,Object> data:dataSet){
						//增加需要删除的id
						if(ApplicationUtils.isNotNull(String.valueOf(data.get("msg_id")))){
							nid.add(String.valueOf(data.get("msg_id")));
						}
					}
					messageBoardMapper.removeMessageBoardById(id);
				}
			}
			if(nid!=null&&nid.size()>0){
				removeMsgById(nid);
			}
		}
	}
	*/
	
	
	
	@Override
	public Map<String, Object> getCommunicationUnreadCount(String token,String cUserID) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}

		//String cUserID = jedisCache.lindex(token, 0);
		List<HashMap> list= messageBoardMapper.getCommunicationUnreadCount(cUserID);

		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");

		return m;
	}
	
	/**
	 * 创建对话并发送第一条信息
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> createCommunication(String token, String content, String password, 
			String communication) throws Exception {
		Map<String, Object> m = new HashMap();
		
		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		
		
		String fromUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		String fromUserMemberName = jedisCache.hget(token, TokenUtil.MEMBER_NAME);

			HashMap hmc=MyTools.checkIsNotNull(communication);
			if(ApplicationUtils.isNotNull(hmc)){
				return hmc;
			}
			
		
		JSONArray json = JSONArray.fromObject(communication);

		// 循环插入数据
		for (int i = 0; i < json.size(); i++) {
			
			JSONObject jsonObject = json.getJSONObject(i);
			String communicationID = (String) jsonObject.get("communicationID");
			String toUserID = (String) jsonObject.get("toUserID");
			String toUserMemberName = (String) jsonObject.get("toUserMemberName");
			
			HashMap hmcc=MyTools.checkIsNotNull(toUserID,toUserMemberName);
			if(hmcc!=null){
				throw new Exception();
			}
			
			if(fromUserID.equals(toUserID)){
				throw new Exception();
			}
			
			
			String uuid=ApplicationUtils.randomUUID();
			
			HashMap hm=new HashMap();
			hm.put("content", content);
			hm.put("password", password);
			hm.put("fromUserID", fromUserID);
			hm.put("fromUserMemberName", fromUserMemberName);
			hm.put("toUserID", toUserID);
			hm.put("toUserMemberName", toUserMemberName);
			
			
			//创建新通道
			if(communicationID==null){
				hm.put("uuid", uuid);
				hm.put("communicationID", uuid);
				//验证通道是否已被建立
				int count=messageBoardMapper.createCommunicationCheckExist(hm);
				if(count!=0){
					throw new Exception();
				}
				//创建新通道
				int effect=messageBoardMapper.createCommunication(hm);
				if(effect!=1){
					throw new Exception();
				}
				
			}else{
				hm.put("uuid", communicationID);
			}

			if (content != null) {
				int effect2 = messageBoardMapper.createCommunicationContent(hm);
				if (effect2 != 1) {
					throw new Exception();
				}
			}

		}

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "发送成功");

		
		return m;
	}
	
	/**
	 * 获得通道列表
	 */
	@Override
	public Map<String, Object> getCommunicationList(String token)
			throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}

		String cUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		List<HashMap> list = messageBoardMapper.getCommunicationList(cUserID);

		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");

		return m;
	}
	
	/**
	 * 验证密码
	 */
	@Override
	public Map<String, Object> checkPassword(String token,String communicationID, String password)
			throws Exception {
		Map<String, Object> m = new HashMap();
		
		
		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		
		HashMap hmc=MyTools.checkIsNotNull(communicationID,password);
		if(hmc!=null){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入必要参数");
			return m;
		}
		
		
		HashMap hm=new HashMap();
		hm.put("communicationID", communicationID);
		hm.put("password", password);
		System.out.println(hm.toString());
		
		
//		String cUserID = jedisCache.lindex(token, 0);
		int count = messageBoardMapper.checkPassword(hm);
		
		if(count==1){
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "验证成功");
		}else{
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证失败");
		}

		return m;
	}
	
	
	/**
	 * 发送内容
	 */
	@Override
	public Map<String, Object> sendMassage(String token, String content, String communication)
			throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		HashMap hmc=MyTools.checkIsNotNull(content,communication);
		if(hmc!=null){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入必要参数");
			return m;
		}
		
		String fromUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		JSONArray json = JSONArray.fromObject(communication);

		// 循环插入数据
		for (int i = 0; i < json.size(); i++) {
			
			JSONObject jsonObject = json.getJSONObject(i);
			String toUserID = (String) jsonObject.get("toUserID");
			String communicationID = (String) jsonObject.get("communicationID");
			
			HashMap hmcc=MyTools.checkIsNotNull(toUserID,communicationID);
			if(hmcc!=null){
				throw new Exception();
			}

			
			
			HashMap hm=new HashMap();
			hm.put("toUserID", toUserID);
			hm.put("communicationID", communicationID);
			hm.put("fromUserID", fromUserID);
			hm.put("content", content);

			System.out.println(hm.toString());
			
			int count = messageBoardMapper.sendMassage(hm);
			
			if(count!=1){
				throw new Exception();
			}
			
		}
		
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "发送成功");
		

		return m;
	}
	
	
	
	/**
	 * 得到交流内容
	 */
	@Override
	public Map<String, Object> getCommunicationContentList(String token, String communicationID, String page_size, 
			String page_index, String skip, String rows) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		HashMap hmc=MyTools.checkIsNotNull(communicationID);
		if(hmc!=null){
			return hmc;
		}
		
		String fromUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
		hm.put("communicationID", communicationID);
		hm.put("fromUserID", fromUserID);

		System.out.println(hm.toString());
		
		
		List<HashMap> list = messageBoardMapper.getCommunicationContentList(hm);
		
		int effect=messageBoardMapper.updateCommunicationContentIsRead(hm);
		
		
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "取数成功");
		
		
		return m;
	}
	
	
	@Override
	public Map<String, Object> getFutureMessageUnreadCount(String token, String cUserID) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		HashMap hmc=MyTools.checkIsNotNull(cUserID);
		if(hmc!=null){
			return hmc;
		}
		
		String fromUserID = jedisCache.hget(token, TokenUtil.USER_ID);
				
		List<HashMap> list = messageBoardMapper.getFutureMessageUnreadCount(cUserID);
		

		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "取数成功");
		
		
		return m;
	}
	
	/**
	 * 创建来自未来的信
	 */
	@Override
	public Map<String, Object> createFutureMessage(String token, String title, String content, 
			String openTime, String user) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		HashMap hmc=MyTools.checkIsNotNull(title,content,openTime,user);
		if(hmc!=null){
			return hmc;
		}
		
		long stime=System.currentTimeMillis(); 
		long popenTime=Long.parseLong(openTime)*1000;
		if(stime>=popenTime){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "只能发送给未来的信");
			return m;
		}
		
		
		
		String fromUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		String fromUserMemberName = jedisCache.hget(token, TokenUtil.MEMBER_NAME);
		
		JSONArray json = JSONArray.fromObject(user);

		// 循环插入数据
		for (int i = 0; i < json.size(); i++) {
			
			JSONObject jsonObject = json.getJSONObject(i);
			String toUserID = (String) jsonObject.get("toUserID");
			String toUserMemberName = (String) jsonObject.get("toUserMemberName");
			
			HashMap hmcc=MyTools.checkIsNotNull(toUserID,toUserMemberName);
			if(hmcc!=null){
				throw new Exception();
			}
			
		
		HashMap hm=new HashMap();
		hm.put("toUserID", toUserID);
		hm.put("toUserMemberName", toUserMemberName);
		hm.put("fromUserID", fromUserID);
		hm.put("fromUserMemberName", fromUserMemberName);
		hm.put("title", title);
		hm.put("content", content);
		hm.put("openTime", openTime);
		
		
		System.out.println(hm.toString());
		
		
		int effect = messageBoardMapper.createFutureMessage(hm);
		if(effect!=1){
			throw new Exception();
		}
		
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "发送成功");
		
		
		return m;
	}
	
	
	
	
	@Override
	public Map<String, Object> getMyFutureMessageList(String token, String page_size, String page_index,
			String skip, String rows) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		String toUserID = jedisCache.hget(token, TokenUtil.USER_ID);
		
		HashMap hm=MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
		hm.put("toUserID", toUserID);

		System.out.println(hm.toString());
		
		List<HashMap> list = messageBoardMapper.getMyFutureMessageList(hm);
		
		
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		
		
		return m;
	}

	
	@Override
	public Map<String, Object> getFutureMessageContent(String token, String board_future_messageID) throws Exception {
		Map<String, Object> m = new HashMap();

		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		List<HashMap> list = messageBoardMapper.getFutureMessageContent(board_future_messageID);
		int effect=messageBoardMapper.updateFutureMessageContentIsRead(board_future_messageID);
		
		m.put(ApplicationUtils.DATASET, list);
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "查询成功");
		
		
		return m;
	}
	
}
